<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Traits\HasUploadedFile;
use Qcloud\Cos\Client;

class FileController
{
    use HasUploadedFile;

    public function handle()
    {
        $disk = $this->disk('local');
        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            try {
                $bucket = env('COSV5_BUCKET'); //存储桶，格式：BucketName-APPID
                $key = parse_url(request()->get('key'))['path'];  //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
                $result = $this->ossClient()->deleteObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                ));
                // 请求成功
            } catch (\Exception $e) {
                // 请求失败
                echo($e);
            }
            // 删除文件并响应
            return $this->deleteFileAndResponse($disk);
        }

        // 获取上传的文件
        $file = $this->file();

        // 获取上传的字段名称

        $key = '/back/' . request()->post('name');
        try {
            $bucket = env('COSV5_BUCKET'); //存储桶名称 格式：BucketName-APPID
            $srcPath = $file->getRealPath();//本地文件绝对路径
            $file = fopen($srcPath, "rb");
            if ($file) {
                $result = $this->ossClient()->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
            }
            @unlink($srcPath);
        } catch (\Exception $e) {
            echo "$e\n";
        }


        return $result
            ? $this->responseUploaded($key,env('COSV5_CDN').$key)
            : $this->responseErrorMessage('文件上传失败');
    }


    public function ossClient()
    {
        // SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
        $secretId = env('COSV5_SECRET_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('COSV5_SECRET_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = env('COSV5_REGION'); //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new Client(
            array(
                'region' => $region,
                'schema' => 'http', //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey)));

        return $cosClient;
    }


}
